﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using Loong.AspNetCore.Mvc.Extensions;
using Loong.AspNetCore.Mvc.Results.Wrapping;
using Loong.Dependency;
using Loong.Reflection;

namespace Loong.AspNetCore.Mvc.Results
{
    public class LoongResultFilter : IResultFilter, ITransientDependency
    {
        private readonly AspNetCoreOptions _options;
        private readonly IActionResultWrapperFactory _actionResultWrapperFactory;

        public LoongResultFilter(
            IOptions<AspNetCoreOptions> options,
            IActionResultWrapperFactory actionResultWrapperFactory)
        {
            _options = options.Value;
            _actionResultWrapperFactory = actionResultWrapperFactory;
        }

        public virtual void OnResultExecuting(ResultExecutingContext context)
        {
            if (!context.ActionDescriptor.IsControllerAction())
            {
                return;
            }

            var wrapResultAttribute =
                ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
                    context.ActionDescriptor.GetMethodInfo(),
                    _options.DefaultWrapResultAttribute
                );

            if (!wrapResultAttribute.WrapOnSuccess)
            {
                return;
            }

            _actionResultWrapperFactory.CreateFor(context).Wrap(context);
        }

        public virtual void OnResultExecuted(ResultExecutedContext context)
        {
        }
    }
}
